<?php
class Pageley_Util_Image {
    private $file;
    private $dimensions;
    
    public function __construct($file) {
        $this->file = $file;
    }
    
    public function getWidth() {
        $dimensions = $this->getDimensions();
        return $dimensions[0];
    }
    
    public function getHeight() {
        $dimensions = $this->getDimensions();
        return $dimensions[1];
    }
    
    private function getDimensions() {
        if($this->dimensions === null) {
            $this->dimensions = getimagesize($this->file->getPath());
        }
        return $this->dimensions;
    }
    
    public function resize($width, $height) {
        $sourceWidth = $this->getWidth();
        $sourceHeight = $this->getHeight();
        $x = 0;
        $y = 0;
        if($width != 0 && $height != 0) {
            $sourceProportion = $sourceWidth / $sourceHeight;
            $proportion = $width / $height;
            if($sourceProportion > $proportion) {
                $x = round(($sourceWidth - $width * $sourceHeight / $height) / 2);
            } else {
                $y = round(($sourceHeight - $height * $sourceWidth / $width) / 2);
            }
        } else if($width != 0) {
            $height = round(($sourceHeight * $width) / $sourceWidth);
        } else if($height != 0) {
            $width = round(($sourceWidth * $height) / $sourceHeight);
        } else {
            $width = $sourceWidth;
            $height = $sourceHeight;
        }
        
        $suffix = "(" . $width . "x" . $height . ")";
        $fileName = $this->file->getNameWithoutExtension();
        $directory = $this->file->getParent()->getPath() . "/";
        $targetFile = new Pageley_Util_File($directory . $fileName . $suffix . ".jpg");
        
        $destination = null;
        if($targetFile->exists()) {
            $destination = imagecreatefromjpeg($targetFile->getPath());
        } else {
            $source = imagecreatefromjpeg($this->file->getPath());
            $destination = imagecreatetruecolor($width, $height);
            imagecopyresampled($destination, $source, 0, 0, $x, $y, $width, $height, $sourceWidth - 2 * $x, $sourceHeight -  2 * $y);
            imagejpeg($destination, $targetFile->getPath(), 90);
            imagedestroy($source);
        }
        imagedestroy($destination);
        return new Pageley_Util_Image($targetFile);
    }
    
    public function getFile() {
        return $this->file;
    }
}